package com.insyte.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.gson.Gson;
import com.insyte.R;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.config.InsyteEnums;
import com.insyte.model.User;
import com.insyte.networks.ParserUtils;
import com.insyte.utils.DialogUtils;
import com.insyte.utils.ToastUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends ActionBarActivity implements View.OnClickListener {
    private ProgressDialog pDialog;
    private Button imgBack;
    private ImageView imgLogo;
    private LinearLayout lnName;
    private RelativeLayout rlFirstName, rlLastName, btn_register, rlCofirmPassword, rlPassword, rlEmail;
    private EditText edtFirstName, edtLastName, edtEmail, edtPassword, edtCofirmPassword;
    private TextView tv_prefix;
    private AQuery aQuery;
    private Map<String, Object> params;
    String url_register = "";
    String url_phone = "/register/phone";
    String url_email = "/register/email";
    float fImgBackW = 61;
    float fImgBackH = 87;
    float fImgLogoW = 362;
    float fImgLogoH = 149;

    //phone register
    private RelativeLayout rlCountryCode, rlPhone, rlSendUpdate;
    private EditText edtPhoneNumber;
    private CheckBox chkSendUpdate;

    InsyteEnums.TypeLogin loginEnum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginEnum = InsyteApp.getTypeLoginEnum(RegisterActivity.this);
        aQuery = new AQuery(this);
        params = new HashMap<String, Object>();
        switch (loginEnum) {
            case EMAIL:
                setContentView(R.layout.activity_register);
                url_register = Constants.URL_API+url_email;
                break;
            case FB:
                break;
            case PHONE:
                setContentView(R.layout.activity_register_phone);
                url_register = Constants.URL_API+url_phone;
                break;
        }
        getView(loginEnum);
        setEvent(loginEnum);
    }

    private void setEvent(InsyteEnums.TypeLogin loginEnum) {
        btn_register.setOnClickListener(this);
        switch (loginEnum) {
            case EMAIL:

                break;
            case PHONE:

                break;
        }
    }

    private void getView(InsyteEnums.TypeLogin loginEnum) {
        btn_register = (RelativeLayout) findViewById(R.id.btn_register);
        imgBack = (Button) findViewById(R.id.imgBack);
        imgBack.setOnClickListener(this);
        imgLogo = (ImageView) findViewById(R.id.imgLogo);
        imgBack.getLayoutParams().width = (int) (fImgBackW * Constants.fScale);
        imgBack.getLayoutParams().height = (int) (fImgBackH * Constants.fScale);
        imgLogo.getLayoutParams().width = (int) (fImgLogoW * Constants.fScale);
        imgLogo.getLayoutParams().height = (int) (fImgLogoH * Constants.fScale);
        switch (loginEnum) {
            case EMAIL:
                lnName = (LinearLayout) findViewById(R.id.lnName);
                rlFirstName = (RelativeLayout) findViewById(R.id.rlFirstName);
                rlLastName = (RelativeLayout) findViewById(R.id.rlLastName);
                rlCofirmPassword = (RelativeLayout) findViewById(R.id.rlCofirmPassword);
                rlPassword = (RelativeLayout) findViewById(R.id.rlPassword);
                rlEmail = (RelativeLayout) findViewById(R.id.rlEmail);
                edtFirstName = (EditText) findViewById(R.id.edtFirstName);
                edtLastName = (EditText) findViewById(R.id.edtLastName);
                edtEmail = (EditText) findViewById(R.id.edtEmail);
                edtPassword = (EditText) findViewById(R.id.edtPassword);
                edtCofirmPassword = (EditText) findViewById(R.id.edtCofirmPassword);
                break;
            case PHONE:
                rlCountryCode = (RelativeLayout) findViewById(R.id.rlCountryCode);
                rlPhone = (RelativeLayout) findViewById(R.id.rlPhone);
                rlSendUpdate = (RelativeLayout) findViewById(R.id.rlSendUpdate);
                edtPhoneNumber = (EditText) findViewById(R.id.edtPhoneNumber);
                chkSendUpdate = (CheckBox) findViewById(R.id.chkSendUpdate);
                tv_prefix = (TextView) findViewById(R.id.tv_prefix);
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
                //submitRegister();
//                new RegisterAsyncTask().execute();
                break;
        }
    }


    protected class RegisterAsyncTask extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(RegisterActivity.this);
            pDialog.setMessage("Saving...");
            pDialog.setCancelable(false);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.show();
        }

        protected String doInBackground(Void... unsued) {
            try {
                String responseString = null;
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url_register);
                httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                try {
                    if (loginEnum == InsyteEnums.TypeLogin.EMAIL) {
                        entity.addPart("first_name", new StringBody(edtFirstName.getText().toString()));
                        entity.addPart("last_name", new StringBody(edtLastName.getText().toString()));
                        entity.addPart("password", new StringBody(edtPassword.getText().toString()));
                        entity.addPart("email", new StringBody(edtEmail.getText().toString()));
                    }
                    if (loginEnum == InsyteEnums.TypeLogin.PHONE) {
                        entity.addPart("phone", new StringBody(edtPhoneNumber.getText().toString()));
                        entity.addPart("prefix", new StringBody(tv_prefix.getText().toString()));
                    }

                    httppost.setEntity(entity);
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(r_entity);
                        Log.e("result", responseString);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }
                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
                }

                return responseString;
            } catch (Exception e) {
                // Toast.makeText(getApplicationContext(),
                // e.getMessage(),
                // Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }
            // (null);
        }

        @Override
        protected void onProgressUpdate(Void... unsued) {

        }

        @Override
        protected void onPostExecute(String sResponse) {
            if (sResponse != null) {
                //ToastUtils.showToast(getApplicationContext(),sResponse);
                try {
                    JSONObject json = new JSONObject(sResponse);
                    pDialog.dismiss();
                    Log.d("json", json.toString());
                    String statusJson = "";
                    String message = "";
                    try {
                        statusJson = json.getString("status");
                        Log.e("", statusJson);
                        if (statusJson.equalsIgnoreCase("OK")) {
                            if (json.getInt("code") == 1) {
                                Gson gson = new Gson();
                                String jsData = json.getString("data");
                                User user = new User();
                                user = gson.fromJson(jsData, User.class);
                                //TODO save user to global or put intent
                                InsyteApp.getInstance().saveUser(user);
                                user.saveUserInformation(getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE));
                                switch (loginEnum) {
                                    case EMAIL:
                                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                        break;
                                    case PHONE:
                                        //showDialogSentVerifyCode();
                                        //Thread.sleep(500L);
                                        Handler handler = new Handler();
                                        handler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                //if (dialogSentVerify.isShowing())dialogSentVerify.dismiss();
                                                startActivity(new Intent(RegisterActivity.this, LoginVerifyPhoneActivity.class));
                                            }
                                        }, 5000);
                                }
                                finish();
                            }
                        } else {
                            message = json.getString("message");
                            JSONArray jArrData = ParserUtils.getJsonArray(json, "data");
                            for (int i = 0; i < jArrData.length(); i++) {
                                message = "\n" + jArrData.getString(i) + "\n";
                            }
                            ToastUtils.showToast(getApplicationContext(), message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (Exception ex) {
                    pDialog.dismiss();
                    ToastUtils.showToast(getApplicationContext(), "Network not available.");
                }
            } else {
                pDialog.dismiss();
                ToastUtils.showToast(getApplicationContext(), "Network not available.");
            }
            pDialog.dismiss();
        }
    }

    private void submitRegister() {
        switch (loginEnum) {
            case EMAIL:
                params = new HashMap<String, Object>();
                params.put("email", edtEmail.getText().toString());
                params.put("first_name", edtFirstName.getText().toString());
                params.put("last_name", edtLastName.getText().toString());
                params.put("password", edtPassword.getText().toString());
                break;
            case PHONE:
                params = new HashMap<String, Object>();
                params.put("phone", edtPhoneNumber.getText().toString());
                params.put("prefix", tv_prefix.getText().toString());
                break;
        }
        runAjaxRegisterEmail();
    }

    private void runAjaxRegisterEmail() {
        aQuery.ajax(url_register, params, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                //Log.e("resutl", result);
                try {
                    JSONObject json = new JSONObject(result);
                    pDialog.dismiss();
                    Log.d("json", json.toString());
                    String statusJson = "";
                    String message = "";
                    try {
                        statusJson = json.getString("status");
                        Log.e("", statusJson);
                        if (statusJson.equalsIgnoreCase("OK")) {
                            if (json.getInt("code") == 1) {
                                Gson gson = new Gson();
                                String jsData = json.getString("data");
                                User user = new User();
                                user = gson.fromJson(jsData, User.class);
                                //TODO save user to global or put intent
                                InsyteApp.getInstance().saveUser(user);
                                user.saveUserInformation(getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE));
                                switch (loginEnum) {
                                    case EMAIL:
                                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                        break;
                                    case PHONE:
                                        //showDialogSentVerifyCode();
                                        //Thread.sleep(500L);
                                        Handler handler = new Handler();
                                        handler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                //if (dialogSentVerify.isShowing())dialogSentVerify.dismiss();
                                                startActivity(new Intent(RegisterActivity.this, LoginVerifyPhoneActivity.class));
                                            }
                                        }, 5000);
                                }
                                finish();
                            }
                        } else {
                            message = json.getString("message");
                            JSONArray jArrData = ParserUtils.getJsonArray(json, "data");
                            for (int i = 0; i < jArrData.length(); i++) {
                                message = "\n" + jArrData.getString(i) + "\n";
                            }
                            ToastUtils.showToast(getApplicationContext(), message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (Exception ex) {
                    pDialog.dismiss();
                    ToastUtils.showToast(getApplicationContext(), "Network not available.");
                }
            }
        }.method(AQuery.METHOD_POST).header("Content-Type", "application/x-www-form-urlencoded"));
    }

}
